package com.mayisoftware.mayioa.business.human.impl.task;

import com.mayisoftware.mayioa.business.human.api.domain.HCInfo;
import com.mayisoftware.mayioa.business.human.api.domain.HCMonitorInfo;
import com.mayisoftware.mayioa.business.human.api.domain.HCUploadInfo;
import com.mayisoftware.mayioa.business.human.api.service.IHCService;
import com.mayisoftware.mayioa.business.human.api.service.IHCUploadService;
import com.mayisoftware.mayioa.business.human.impl.dao.HCMapper;
import com.mayisoftware.mayioa.common.impl.utils.DateUtils;
import com.mayisoftware.mayioa.common.impl.utils.ExcelReadWriteUtils;
import com.mayisoftware.mayioa.platform.api.service.ISysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 定时任务调度计划解析
 *
 *
 */
@Component("hcFileParseTask")
public class HCFileParseTask
{
    /**
     * 日志对象
     */
    private static final Logger log = LoggerFactory.getLogger(HCFileParseTask.class);


    /**
     * 上传记录操作服务
     */
    @Autowired
    private HCMapper hcMapper;
    /**
     * 上传记录操作服务
     */
    @Autowired
    private IHCUploadService uploadRecordService;

    @Autowired
    private IHCService hcService;

    /**
     * 用户管理服务
     */
    @Autowired
    private ISysUserService sysUserService;

    public void parseHCFiles()
    {
//        log.info("开始执行工时文件解析");

        try {
            //查询数据库记录
            List<HCUploadInfo> uploadRecords = uploadRecordService.queryRecordListNeedParse();

            if(CollectionUtils.isEmpty(uploadRecords)){
                return;
            }

            String errorFilePath = "";
            for (HCUploadInfo record:uploadRecords){
                boolean isOk = true;
                HCUploadInfo updateRecord = new HCUploadInfo();
                try {
                    log.info("处理记录 id: {} 文件:{}",record.getImportId(),record.getFilePath());
                    String filePath = record.getFilePath();

                    File file =new File(filePath);
                    if(!file.exists() || !file.isFile()){
                        log.error("处理记录 id: {} 文件:{}不存在",record.getImportId(),record.getFilePath());
                        continue;
                    }

                    String fileName= file.getName();
                    String fileDir=file.getParentFile().getAbsolutePath();
                    String fileNameNoExt = fileName.substring(0,fileName.lastIndexOf("."));
                    errorFilePath = fileDir+File.separator+fileNameNoExt+".log";

                    updateRecord.setImportId(record.getImportId());
                    //更新DB状态 正在解析
                    updateRecord.setParseStatus("2");

                    uploadRecordService.editInputRecord(updateRecord);

//                    StringBuffer planBuffer =new StringBuffer();
                    analysisOneFile(filePath);
//                    isOk = dealOneUploadFile(record,file,errorFilePath,fileDir,planBuffer );
//                    updateRecord.setPlanName(planBuffer.toString());
                }
                catch (Exception e){
                    log.error("处理记录 id: {} 文件:{},异常",record.getImportId(),record.getFilePath(),e);
                }
                finally {
                    try {
                        if (isOk){
                            log.info("处理记录 id: {} 文件:{},处理成功",record.getImportId(),record.getFilePath());
                            //更新DB状态 正在解析

                            updateRecord.setParseStatus("3");
                            uploadRecordService.editInputRecord(updateRecord);
                        }
                        else {
                            log.info("处理记录 id: {} 文件:{},处理失败",record.getImportId(),record.getFilePath());
                            //更新DB状态 正在解析
                            updateRecord.setParseStatus("4");
                            updateRecord.setErrorPath(errorFilePath);
                            uploadRecordService.editInputRecord(updateRecord);
                        }
                    }
                    catch (Exception e){
                        log.info("处理记录状态异常",e);
                    }
                }
            }
        } catch (Exception e) {
            log.error("执行计划解析异常",e);
        }

//        log.info("结束执行计划解析");
//        poolManualService.modifyPoolInfoToCacl();
    }

    /**
     * 处理一个上传记录文件
     */
//    private boolean dealOneUploadFile(HCUploadInfo record, File file,String  errorFilePath, String dstDirectoryPath,StringBuffer planBuffer) {
//
//        String filePath = file.getAbsolutePath();
//        String unzipDir = "";
//
//        try {
//            if (filePath.toLowerCase().endsWith(".rar")) {
//                FileUnZipRar.unRarFile(filePath, dstDirectoryPath);
//            } else if (filePath.toLowerCase().endsWith(".zip")) {
//                unzipDir = UnZipFile.unZipFile(file, dstDirectoryPath);
//            }
//        }catch (Exception ex){
//            log.error("解压缩文件发生异常！"+ex.getMessage());
//            return false;
//        }
//
//        return analysisOneFile(unzipDir);
//    }

    /**
     * 统计分析主方法
     * @param filePath TM文件路径
     * @return 0：成功，-1：失败
     */
    private   boolean analysisOneFile(String filePath){
        File pathFile = new File(filePath);

        HCUploadInfo tmFileInfo = new HCUploadInfo();
        tmFileInfo.setFileName(pathFile.getAbsolutePath());
        if (!check(tmFileInfo)){
            log.error("解析文件失败。。。");
            return false;
        }
        return  true;
    }

    public boolean check(HCUploadInfo hcUploadInfo){

        try{
            List<HCInfo> hcs = getHCInfoList(hcUploadInfo);

            if (hcs==null){
                return false;
            }

            for (HCInfo hc : hcs) {
                int existCount = hcMapper.isHCExist(hc);
                if (existCount==0){
                    hcMapper.insertHC(hc);
                }

                HCMonitorInfo hcMonitorInfo=new HCMonitorInfo();
                hcMonitorInfo.setHcId(hc.getHcId());
                hcMonitorInfo.setCheckPeriod(hcService.getDictValue("check_period",uploadRecordService.getCheckPeriod(hc.getHumanInvalidDate())));
                int records = hcService.isHCMonitorExist(hcMonitorInfo);
                if (records==0) {
                    records = hcService.insertHCMonitor(hcMonitorInfo);
                }
            }

        }catch (Exception ex){
            log.error(ex.getMessage());
            return false;
        }

        return  true;
    }


    private List<HCInfo> getHCInfoList(HCUploadInfo hcUploadInfo){
        List<HCInfo> retList = new ArrayList<>();
        File detailFile = new File(hcUploadInfo.getFileName());
        List<String> contents =null;
        try {
            contents= ExcelReadWriteUtils.readExcelList(detailFile.getAbsolutePath(),1);
        } catch (InvalidFormatException e) {
            e.printStackTrace();
            return retList;
        } catch (IOException e) {
            e.printStackTrace();
            return retList;
        }

        int count = 0;
        for (String item: contents) {
            count++;
            if (count <= 2) {
                continue;
            }

            List<String> items = Arrays.asList(item.split(","));
            if (items==null || items.size()==0){
                continue;
            }
            HCInfo hcInfo = new HCInfo();
//            2	sendDate
//            4	sendName
//            5	delegate
//            9	pdu
//            11	expenseType
//            12	region
//            14	skillType
//            15	prjId
//            16	prj_name
//            17	postName/HumanRole
//            18	hwLevel
//            19	humanInvalidDate
//            21	hcId
//            23	humanRemark
            hcInfo.setSendDate(DateUtils.dateTime(DateUtils.YYYY_MM_DD,items.get(2)));
            hcInfo.setSendName(items.get(4));
            hcInfo.setDelegate(items.get(5));
//            hcInfo.setPdu(items.get(9));
            hcInfo.setPdu(hcService.getDictValue("human_pdu",items.get(9)));

            hcInfo.setExpenseType(items.get(11));
//            hcInfo.setRegion(items.get(12));
            hcInfo.setRegion(hcService.getDictValue("check_region",items.get(12)));
            hcInfo.setSkillType(items.get(14));
            hcInfo.setPrjId(items.get(15));
            hcInfo.setPrj_name(items.get(16));

            hcInfo.setPostName(items.get(17));
            hcInfo.setHumanRole(items.get(17));
            hcInfo.setHwLevel(items.get(18));
            hcInfo.setHumanInvalidDate(DateUtils.dateTime(DateUtils.YYYY_MM_DD,items.get(19)));
            hcInfo.setHcId(items.get(21));
            hcInfo.setHumanRemark(items.get(23));
            retList.add(hcInfo);
        }

        return retList;
    }

}
